package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmUpdateDataService;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasProcessDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.SheetTypeEnum;
import com.xbongbong.paas.enums.TaskTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.UserHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.vo.FormDataUpdateVO;
import com.xbongbong.paas.service.ProModelService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.parent.pojo.UpdateValidateReturnPojo;
import com.xbongbong.pro.domain.entity.ReRollBackEntity;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.vo.BeforeUpdateVO;
import com.xbongbong.pro.formdata.pojo.vo.UpdateVO;
import com.xbongbong.pro.sheet.pojo.SheetAttrPojo;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.PaymentSheetUserEntity;
import com.xbongbong.saas.domain.entity.ext.PaymentSheetEntityExt;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.help.FundHelp;
import com.xbongbong.saas.help.SaasUpdateHelp;
import com.xbongbong.saas.model.PaymentSheetModel;
import com.xbongbong.saas.model.PaymentSheetUserModel;
import com.xbongbong.saas.service.PaymentSheetService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/02/23 16:03
 */
@Service("paymentSheetFormDataUpdateServiceImpl")
public class PaymentSheetFormDataUpdateServiceImpl extends AbstractCrmUpdateDataService {

    private static final Logger LOG = LoggerFactory.getLogger(PaymentSheetFormDataUpdateServiceImpl.class);

    @Resource
    private UserHelp userHelp;
    @Resource
    private ProModelService proModelService;
    @Resource
    private PaymentSheetModel paymentSheetModel;
    @Resource
    private FundHelp fundHelp;
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;

    @Resource
    private SaasUpdateHelp saasUpdateHelp;
    @Resource
    private PaymentSheetService paymentSheetService;
    @Resource
    private PaymentSheetUserModel paymentSheetUserModel;

    @Override
    public List<Integer> businessType() {
        return Arrays.asList(XbbRefTypeEnum.PAYMENT_SHEET.getCode(),
                XbbRefTypeEnum.BAD_DEBT.getCode(),
                XbbRefTypeEnum.WRITE_OFF_PREPAYMENT.getCode(),
                XbbRefTypeEnum.RED_PAYMENT_SHEET.getCode(),
                XbbRefTypeEnum.RED_WRITE_OFF_PREPAYMENT.getCode(),
                XbbRefTypeEnum.RED_PREPAYMENT.getCode(),
                XbbRefTypeEnum.PREPAYMENT.getCode());
    }

    @Override
    public UpdateValidateReturnPojo analyticalData(FormDataUpdateDTO formDataUpdateDTO, ValidateDataDTO validateDataDTO, PaasFormDataEntity oldPaasFormDataEntity, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        JSONArray amountDetail = FastJsonHelper.getAmountDetail(formDataUpdateDTO.getDataList());
        validateDataDTO.setAmountDetail(amountDetail);
        return super.analyticalData(formDataUpdateDTO, validateDataDTO, oldPaasFormDataEntity, explainMap);
    }

    @Override
    public void afterSaveLog(FormDataUpdateDTO formDataUpdateDTO, PaasFormEntityExt paasFormEntityExt, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity, UpdateVO updateVO, BeforeUpdateVO beforeUpdateVO) throws XbbException {
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.PAYMENT_SHEET;
        boolean isCoverage = Objects.equals(1, formDataUpdateDTO.getIsCover());
        if(isCoverage){
           return;
        }
        // 记录日志

        String memoName = paasFormEntityExt.getName();
        String userName = updateVO.getUserVO().getName();
        String opObjectName = paasFormDataEntity.getSerialNo();
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_WORK), userName, memoName, opObjectName);
// 负责人是获取当前登录人的ID，不准确,所属部门也没有模版字段，舍去
        paasFormDataEntity.setOwnerId(null);
        //paasFormDataEntity.setDepartmentId(null);
        saveLogger(formDataUpdateDTO, paasFormDataEntity, redundantTemplateTypeEnum, memo, opObjectName, OperateModuleTypeEnum.PAYMENT_SHEET, updateVO, beforeUpdateVO,
                OperateTypeEnum.EDIT, IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET_SUB);

    }

    @Override
    public UpdateVO update(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        try {
            String corpid = formDataUpdateDTO.getCorpid();
            UserVO userVO = userHelp.getUserName(formDataUpdateDTO.getCorpid(), formDataUpdateDTO.getUserId(), formDataUpdateDTO.getLoginUserName(), beforeUpdateVO.getPaasFormDataEntity().getFlowStatus(), beforeUpdateVO.getPaasFormDataEntity().getCreatorId());
            Integer noApprovalRequired = beforeUpdateVO.getNoApprovalRequired();
            Integer updateLine = 0;
            if ( Objects.equals(noApprovalRequired, 1) ) {
                JSONObject data = paasFormDataEntity.getData();
                JSONObject oldData = oldPaasFormDataEntity.getData();
                SheetTypeEnum sheetTypeEnum = SheetTypeEnum.getByCodeRefTypeEnum(data.getString(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr()), XbbRefTypeEnum.PAYMENT_SHEET);
                data = fundHelp.handlePaymentSheetData4Update(sheetTypeEnum, data, oldData, formDataUpdateDTO.getDistributorMark(), null);
                FormDataUtil.removeSystemData(data);
                Object richTextData = removeRichText(data);
                paasFormDataEntity.setData(data);
                PaymentSheetEntityExt paymentSheetEntityExt = new PaymentSheetEntityExt();
                BeanUtil.copyProperties(paasFormDataEntity, paymentSheetEntityExt);
                updateLine = paymentSheetModel.update(paymentSheetEntityExt);


                // 设置属性用于返回
                setPartialAttributes(paymentSheetEntityExt.getSubFormData(), paymentSheetEntityExt.getData(),
                        paymentSheetEntityExt.getUpdateTime(), paymentSheetEntityExt.getAddTime(), paymentSheetEntityExt.getSerialNo(),
                        paymentSheetEntityExt.getDepartmentId(), paymentSheetEntityExt.getOwnerId(),
                        paasFormDataEntity, beforeUpdateVO);
                //文件柜数据保存
                saveFile(formDataUpdateDTO, paasFormDataEntity, userVO);
                //富文本数据更新
                updateFormRichText(formDataUpdateDTO, richTextData);
            }
            return new UpdateVO(noApprovalRequired, paasFormDataEntity, updateLine, formDataUpdateDTO.getDataId(), userVO);
        } catch (XbbException e) {
            afterSaveRollBack(formDataUpdateDTO, null, beforeUpdateVO, new ReRollBackEntity());
            throw e;
        } catch (Exception e) {
            afterSaveRollBack(formDataUpdateDTO, null, beforeUpdateVO, new ReRollBackEntity());
            LOG.error("purchaseInvoiceFormDataUpdateServiceImpl.update 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }


    @Override
    public FormDataUpdateVO afterSave(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, UpdateVO updateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        String corpid = formDataUpdateDTO.getCorpid();
        Long dataId = formDataUpdateDTO.getDataId();
        Integer businessType = formDataUpdateDTO.getBusinessType();
        try {
            FormDataUpdateVO formDataUpdateVO = new FormDataUpdateVO();
            Integer noApprovalRequired = updateVO.getNoApprovalRequired();
            if (Objects.equals(1, noApprovalRequired)) {
                SheetTypeEnum sheetTypeEnum = SheetTypeEnum.getByCodeRefTypeEnum(paasFormDataEntity.getData().getString(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr()), XbbRefTypeEnum.PAYMENT_SHEET);

                //更新子单信息
                JSONArray amountDetailJsonArray = new JSONArray();
                JSONArray newCloneJsonArray = new JSONArray();
                if (Objects.nonNull(formDataUpdateDTO.getAmountDetail())) {
                    amountDetailJsonArray = formDataUpdateDTO.getAmountDetail();
                }else if(Objects.nonNull(formDataUpdateDTO.getSaasNeedRedundantAttrPoJo())) {
                    //主要是为了兼容编辑回款单进审批的场景
                    amountDetailJsonArray = formDataUpdateDTO.getSaasNeedRedundantAttrPoJo().getAmountDetail();
                }
                newCloneJsonArray = (JSONArray) CloneUtil.deepClone(amountDetailJsonArray);
                List<UpdateDataEntity> updateList = saasUpdateHelp.updateSonDataList4Sheet(corpid, sheetTypeEnum, newCloneJsonArray,
                        formDataUpdateDTO.getExplainMap(), formDataUpdateDTO.getDistributorMark());
                if (CollectionsUtil.isNotEmpty(updateList)) {
                    updateList.forEach(updateDataEntity -> {
                        if (Objects.nonNull(updateVO.getPaasFormDataEntity())) {
                            updateDataEntity.setFlowStatus(updateVO.getPaasFormDataEntity().getFlowStatus());
                        }
                    });
                    paymentSheetModel.updateBatch(updateList, corpid);
                }
                // 日志
                afterSaveLog(formDataUpdateDTO, paasFormEntity, paasFormDataEntity, oldPaasFormDataEntity, updateVO, beforeUpdateVO);
                // api发起
                apiHook(formDataUpdateDTO, updateVO, beforeUpdateVO);

                // 2021/3/3 业务规则
                activeRule(formDataUpdateDTO, beforeUpdateVO, updateVO);
                formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
                formDataUpdateVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
            } else if (Objects.equals(noApprovalRequired, 2)) {
                // 自动拒绝
                formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_PROCESS_RETURN_MSG));
                formDataUpdateVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
            } else {
                formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_PROCESS_RETURN_MSG));
                formDataUpdateVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
                PaasProcessDataEntity paasProcessDataEntity = new PaasProcessDataEntity();
                paasProcessDataEntity.setCorpid(formDataUpdateDTO.getCorpid());
                paasProcessDataEntity.setFormDataId(dataId);
                paasProcessDataEntity.setBusinessType(businessType);
                paasProcessDataEntity.setSaasMark(formDataUpdateDTO.getSaasMark());
                proModelService.updateFormDataStatus(paasProcessDataEntity, FlowStatusEnum.IN_APPROVAL.getType());
            }
            formDataUpdateVO.setFormDataId(dataId);
            return formDataUpdateVO;
        } catch (XbbException e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            throw e;
        } catch (Exception e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            LOG.error("purchaseInvoiceFormDataUpdateServiceImpl.afterSave 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public void apiHook(FormDataUpdateDTO formDataUpdateDTO, UpdateVO updateVO, BeforeUpdateVO beforeUpdateVO) throws XbbException {
        // 第三方服务
        lowCodeExecuteService(formDataUpdateDTO, updateVO, beforeUpdateVO);
    }

    @Override
    public UpdateVO updateForWorkflow(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        try {
            UserVO userVO = userHelp.getUserName(formDataUpdateDTO.getCorpid(), formDataUpdateDTO.getUserId(), formDataUpdateDTO.getLoginUserName(), beforeUpdateVO.getPaasFormDataEntity().getFlowStatus(), beforeUpdateVO.getPaasFormDataEntity().getCreatorId());
            Integer noApprovalRequired = beforeUpdateVO.getNoApprovalRequired();
            Integer updateLine = 0;
            JSONObject data = paasFormDataEntity.getData();
            JSONObject oldData = oldPaasFormDataEntity.getData();
            SheetTypeEnum sheetTypeEnum = SheetTypeEnum.getByCodeRefTypeEnum(data.getString(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr()), XbbRefTypeEnum.PAYMENT_SHEET);
            if (Objects.equals(formDataUpdateDTO.getTaskType(), TaskTypeEnum.AGAIN_COMMIT.getType())){
                SheetAttrPojo sheetAttrPojo = new SheetAttrPojo(sheetTypeEnum.getXbbRefTypeEnum());
                fundHelp.formatAmountWriteOff(null, sheetTypeEnum, sheetAttrPojo, data);
            }else {
                //重新提交不走这个方法
                data = fundHelp.handlePaymentSheetData4WorkflowUpdate(sheetTypeEnum, data, oldData, formDataUpdateDTO.getDistributorMark(), null);
            }
            paasFormDataEntity.setData(data);
            PaymentSheetEntityExt paymentSheetEntityExt = new PaymentSheetEntityExt();
            BeanUtil.copyProperties(paasFormDataEntity, paymentSheetEntityExt);
            FormDataUtil.removeSystemData(paymentSheetEntityExt.getData());
            Object richTextData = removeRichText(paymentSheetEntityExt.getData());
            updateLine = paymentSheetModel.update(paymentSheetEntityExt);
            // 设置属性用于返回
            setPartialAttributes(paymentSheetEntityExt.getSubFormData(), paymentSheetEntityExt.getData(),
                    paymentSheetEntityExt.getUpdateTime(), paymentSheetEntityExt.getAddTime(), paymentSheetEntityExt.getSerialNo(),
                    paymentSheetEntityExt.getDepartmentId(), paymentSheetEntityExt.getOwnerId(),
                    paasFormDataEntity, beforeUpdateVO);
            //文件柜数据保存
//            saveFile(formDataUpdateDTO, paasFormDataEntity, userVO);
            //富文本数据保存
            Integer updateRichTextLine = updateFormRichText(formDataUpdateDTO, richTextData);
            //表单数据和富文本数据其中有一个编辑就要进工作流
            updateLine = Objects.equals(updateLine, 1) || Objects.equals(updateRichTextLine, 1) ? 1 : 0;
            return new UpdateVO(noApprovalRequired, paasFormDataEntity, updateLine, formDataUpdateDTO.getDataId(), userVO);
        } catch (XbbException e) {
            afterSaveRollBack(formDataUpdateDTO, null, beforeUpdateVO, new ReRollBackEntity());
            throw e;
        } catch (Exception e) {
            afterSaveRollBack(formDataUpdateDTO, null, beforeUpdateVO, new ReRollBackEntity());
            LOG.error("purchaseInvoiceFormDataUpdateServiceImpl.update 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public FormDataUpdateVO afterSaveForWorkflow(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, UpdateVO updateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        String corpid = formDataUpdateDTO.getCorpid();
        Long dataId = formDataUpdateDTO.getDataId();
        Integer businessType = formDataUpdateDTO.getBusinessType();
        try {
            FormDataUpdateVO formDataUpdateVO = new FormDataUpdateVO();
            Integer noApprovalRequired = updateVO.getNoApprovalRequired();
            SheetTypeEnum sheetTypeEnum = SheetTypeEnum.getByCodeRefTypeEnum(paasFormDataEntity.getData().getString(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr()), XbbRefTypeEnum.PAYMENT_SHEET);

            SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
            BeanUtil.copyProperties(formDataUpdateDTO, saasFormSaveDTO);
            packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, beforeUpdateVO.getOldPaasFormData());
            paymentSheetService.afterSaveForUpdateWorkflow(saasFormSaveDTO);
            //更新子单信息
            /*List<UpdateDataEntity> updateList = saasUpdateHelp.updateSonDataList4Sheet(corpid, sheetTypeEnum, formDataUpdateDTO.getAmountDetail(), formDataUpdateDTO.getExplainMap(), formDataUpdateDTO.getDistributorMark());
            if (CollectionsUtil.isNotEmpty(updateList)) {
                paymentSheetModel.updateBatch(updateList, corpid);
            }*/
            // 日志
//            afterSaveLog(formDataUpdateDTO, paasFormDataEntity, updateVO, beforeUpdateVO);
            // api发起
//            apiHook(formDataUpdateDTO, updateVO, beforeUpdateVO);

            // 2021/3/3 业务规则
//            activeRule(formDataUpdateDTO, beforeUpdateVO, updateVO);

            formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
            formDataUpdateVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
//            PaasProcessDataEntity paasProcessDataEntity = new PaasProcessDataEntity();
//            paasProcessDataEntity.setCorpid(formDataUpdateDTO.getCorpid());
//            paasProcessDataEntity.setFormDataId(dataId);
//            paasProcessDataEntity.setBusinessType(businessType);
//            paasProcessDataEntity.setSaasMark(formDataUpdateDTO.getSaasMark());
//            proModelService.updateFormDataStatus(paasProcessDataEntity, FlowStatusEnum.IN_APPROVAL.getType());

            formDataUpdateVO.setFormDataId(dataId);
            return formDataUpdateVO;
        } catch (Exception e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            LOG.error("purchaseInvoiceFormDataUpdateServiceImpl.afterSave 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public Long backupData(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) {
        String corpid = formDataUpdateDTO.getCorpid();
        Integer isProcessForm = paasFormEntity.getIsProcessForm();
        if (!formDataUpdateDTO.getIsSatisfyTrigger()) {
            return null;
        }
        JSONObject data = oldPaasFormDataEntity.getData();
        setSystemData(data, oldPaasFormDataEntity);

        long now = DateTimeUtil.getInt();
        data = backupDataOtherInfo(data, corpid, oldPaasFormDataEntity.getId());
        WorkflowBackupDataEntity workflowBackupDataEntity = new WorkflowBackupDataEntity(corpid, oldPaasFormDataEntity.getAppId(), oldPaasFormDataEntity.getFormId(), oldPaasFormDataEntity.getMenuId(), 0L, 0L, oldPaasFormDataEntity.getId(), data, now, now, DelEnum.NORMAL.getDel());
        workflowBackupDataModel.insert(workflowBackupDataEntity);
        return workflowBackupDataEntity.getId();
    }

    @Override
    public JSONObject backupDataOtherInfo(JSONObject data, String corpid, Long dataId) {
        List<PaymentSheetUserEntity> paymentSheetUserIdList = paymentSheetUserModel.getPaymentSheetUserIdList(corpid, dataId, null);
        data.put(StringConstant.USER_TEAM, paymentSheetUserIdList);
        return data;
    }
}
